<?php
namespace ZfcUser\Model;

use Zend\Db\ResultSet\ResultSet;
use Zend\Db\TableGateway\TableGateway;
use Zend\Db\Sql;
use Zend\Db\Sql\Where;
use Zend\Db\Sql\Select;
use Zend\Paginator\Adapter\DbSelect;
use Zend\Paginator\Paginator;
use Zend\Db\Sql\Expression;
class TstudentandmentorTable
{
    protected $tableGateway;
	protected $select;
    public function __construct(TableGateway $tableGateway)
    {
        $this->tableGateway = $tableGateway;
		$this->select = new Select();
    }	
	public function addRelation($id){
		$studentId=$_SESSION['user']['userId'];
		$data=array(
			'student_id'	=>	$studentId,
			'mentor_id'		=>	$id,
			'status'		=>	0,
		);
		$this->tableGateway->insert($data);
		$select = $this->tableGateway->getSql()->select()
				->where('student_id="'.$studentId.'"')
				->where('mentor_id="'.$id.'"');				
		$resultSet = $this->tableGateway->selectWith($select);
		$row = $resultSet->current();
		return $row;      
    }	
	public function changeStatus($ids,$value){
		$mentorId=$_SESSION['user']['userId'];
		$data = array(
			'status' =>	$value,
		);
		$row=$this->tableGateway->update($data, array('id' => $ids));
		return 	$row;	
	}
	public function checkRelation($mId,$sId)
    {		
		$select = $this->tableGateway->getSql()->select()
				->where('student_id="'.$sId.'"')
				->where('mentor_id="'.$mId.'"');
		$resultSet = $this->tableGateway->selectWith($select);				
        return $resultSet->count();
	}
	public function getAll($userId,$type){
		$select = $this->tableGateway->getSql()->select();
		if($type=='student'){
			$select	->join('t_user', 't_user.user_id=t_student_and_mentor.mentor_id',array('*'),'left');
		}else{
			$select	->join('t_user', 't_user.user_id=t_student_and_mentor.student_id',array('*'),'left');
		}
		$select	->join('t_user_type', 't_user_type.user_type_id=t_user.user_type_id',array('*'),'left');
		if($type=='student'){
			$select	->where('t_student_and_mentor.student_id="'.$userId.'"');
		}else{
			$select	->where('t_student_and_mentor.mentor_id="'.$userId.'"');
		}
		$select	->order('t_student_and_mentor.id DESC');		
		$resultSet = $this->tableGateway->selectWith($select);
		return $resultSet;
	}
	public function deleteOperation($ids){
		$studentId=$_SESSION['user']['userId'];
		$this->tableGateway->delete(array('(id IN ('.$ids.'))'));	
		return $this->tableGateway->lastInsertValue;	
	}
}